//package com.example.demo.config.shiro;
//
//import com.example.demo.util.PasswordUtil;
//import net.sf.ehcache.Ehcache;
//import net.sf.ehcache.Element;
//import org.apache.shiro.authc.*;
//import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
//import org.apache.shiro.cache.ehcache.EhCacheManager;
//import org.apache.shiro.codec.CodecSupport;
//import org.apache.shiro.util.ByteSource;
//
//import java.util.concurrent.atomic.AtomicInteger;
//
///**
// * Description: 告诉shiro如何验证加密密码，通过SimpleCredentialsMatcher或HashedCredentialsMatcher
// */
//public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {
//
//    private final static String CACHE_NAME = "Matcher";
//
//    Ehcache cache;
//
//    public CustomCredentialsMatcher(EhCacheManager ehCacheManager) {
//        super();
//        cache = ehCacheManager.getCacheManager().addCacheIfAbsent(CACHE_NAME);
//    }
//
//    /**
//     *
//     * @param authcToken 用户输入的密码
//     * @param info       数据库读出来的密码, AuthorizingRealm.doGetAuthenticationInfo返回值
//     * @return
//     */
//    @Override
//    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
////        super.doCredentialsMatch(authcToken, info);
//        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//
//        String username = info.getPrincipals().getPrimaryPrincipal().toString();
//
//        Element element = cache.get(username);
//        if(element == null) {
//            element = new Element(username , new AtomicInteger(0));
//            cache.put(element);
//        }
//        // 尝试次数超过5次就锁定
//        AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();
//        if(retryCount.incrementAndGet() > 5) {
//            //if retry count > 5 throw
//            throw new ExcessiveAttemptsException();
//        }
//
//        String encryptPassword = info.getCredentials().toString();
//
//        ByteSource credentialsSalt = ((SimpleAuthenticationInfo) info).getCredentialsSalt();
//        if (PasswordUtil.matches(new String(token.getPassword()), encryptPassword, CodecSupport.toString(credentialsSalt.getBytes()))) {
//            cache.remove(username);
//            return Boolean.TRUE;
//        }
//
//        return Boolean.FALSE;
//
//    }
//
//}
